/**
 * @file
 * @auth jinguangguo
 * @date 2016/11/1
 */

import ajaxPc from '../util/ajax';
import ajaxMobile from '../util/ajaxMobile';
import commonUtil from './commonUtil';

let isMobile = commonUtil.isMobile();

// 包括实时成交、挂单、当前委托、k线等
let normalLoopTime = 1000;
if (isMobile === true) {
    normalLoopTime = 5000;
}

let ajax = ajaxPc;
if (isMobile === true) {
    ajax = ajaxPc;
}

export default {
    /**
     * 总资产数据
     * @param param
     * @returns {*}
     * */
    getTotalAssets(param = {}, header) {
        return ajax.get('/exchangeApi/asset/accounts', {
            data: param,
            header: header
        });
    },

    /**
     * 获取bitfinex的BTC的价格
     */
    getBitfinexBtcPrice(param = {}) {
        // let deferred = $.Deferred();
        // return $.ajax({
        //     url: 'http://api.bitfinex.com/v1/pubticker/BTCUSD',
        //     type: 'GET',
        //     dataType: 'JSON',
        //     success(rep) {
        //         debugger;
        //     }
        // });
        // return deferred.promise();

        return ajax.get('/exchangeApi/common/usdbtc', {
            data: param
        });
    },

    /**
     * 获取交易手续费
     * @param param
     * @returns {*}
     */
    getTradeFee(param = {}) {
        return ajax.get('/exchangeApi/match/config-list', {
            data: param
        });
    },
    /**
     * 获取公告
     * @param param
     * @returns {*}
     */
    getNotice(param = {}) {
        return ajax.send('/noticeApi/noticeList', {
            data: param
        });
    },

    /**
     * 获取图形验证码
     * @returns {string}
     */
    getCode(param = {}) {

        let deferred = $.Deferred();
        if (window.app.DEBUG === true && window.location.port === '8000') {
            $.ajax({
                url: '/exchangeApi/captchar/code?randomKey=' + param.randomKey,
                type: 'POST',
                dataType: 'JSON',
                contentType: 'application/json; charset=UTF-8',
                success: function(rep) {
                    deferred.resolveWith(this, [rep]);
                },
                error: function(xhr, type) {
                    deferred.resolveWith(this, [xhr.responseText]);
                }
            });
        } else {
            let rep = '/exchangeApi/captchar/code?randomKey=' + param.randomKey;
            deferred.resolveWith(this, [rep]);
        }

        return deferred.promise();

    },


    /**
     * 登录是否需要图形验证码
     *
     */
    needCaptha(param = {}, header = {}) {
        return ajax.get('/exchangeApi/user/need-captha', {
            data: param,
            header: header
        })
    },


    /**
     * 图形验证码是否成功
     * @param param
     * @returns {*}
     */
    isIdentifyCaptchar(param = {}) {
        return ajax.send('/exchangeApi/common/identifyCaptchar', {
            data: param
        });
    },

    /**
     * 资金密码是否被锁定
     * 注: 暂时还没有使用
     * @param param
     * @returns {*}
     */
    isPayLocked(param = {}) {
        return ajax.send('/exchangeApi/security/isPayLocked', {
            data: param
        });
    },

    /**
     * 轮训交易
     */
    onLoopTradeInfo: (function() {
        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback, param) {
            let isLoop = true;
            let that = this;

            let returnObj = {
                clear() {
                    isLoop = false;
                    hasRequested = false;
                    isRequesting = false;
                }
            };

            callbacks.push(callback);
            // console.log('push...');

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return returnObj;
            } else {
                hasRequested = true;
            }


            if (isRequesting === true) {
                return returnObj;
            } else {
                loop();
            }

            function loop() {
                isRequesting = true;
                that.loopTradeInfo(param).then((rep) => {
                    // console.log('callback...');
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        // 非调试状态下
                        if (window.app.DEBUG === false && isLoop === true) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
            return returnObj;
        };

    })(),

    /**
     * 轮训查询
     * @param param
     * @returns {*}
     */
    loopTradeInfo(param = {}) {
        return ajax.getHttpQuote('/trade/info', {
            data: param
        }, false);
    },

    /**
     * 轮训买卖盘
     */
    onLoopTradeGetList: (function() {

        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback, param) {
            let isLoop = true;
            let that = this;
            let timer = null;

            let returnObj = {
                clear() {
                    isLoop = false;
                    hasRequested = false;
                    isRequesting = false;
                }
            };

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return returnObj;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return returnObj;
            } else {
                loop();
            }

            function loop() {
                isRequesting = true;
                that.loopTradeGetList(param).then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    timer = setTimeout(() => {
                        if (window.app.DEBUG === false && isLoop === true) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
            return returnObj;
        };

    })(),

    onLoopTradeTrade: (function() {

        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback, param) {
            let isLoop = true;
            let that = this;
            let timer = null;

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return;
            } else {
                loop();
            }

            function loop() {
                isRequesting = true;
                that.loopTradeGetList(param).then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    timer = setTimeout(() => {
                        if (window.app.DEBUG === false && isLoop === true) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
            return () => {
                clearInterval(timer);
                isLoop = false;
                hasRequested = false;
                isRequesting = false;
            }
        };

    })(),

    /**
     * 轮训查询买卖盘
     * @param param
     * @returns {*}
     */
    loopTradeGetList(param = {}) {
        return ajax.getHttpQuote('/trade/trade', {
            data: param
        });
    },

    /**
     * 轮训深度图
     */
    onLoopDepthMap: (function() {
        const LOOP_TIME = 3000;
        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback, symbol) {
            let that = this;

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return;
            } else {
                loop();
            }

            function loop() {
                isRequesting = true;
                that.loopDepthMap(symbol).then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        if (window.app.DEBUG === false) {
                            loop();
                        }
                    }, LOOP_TIME)
                });
            }
        };

    })(),

    /**
     * 轮训查询买卖盘
     * @param param
     * @returns {*}
     */
    loopDepthMap(param = {}) {
        return ajax.getHttpQuote('/trade/depth', {
            data: param
        });
    },

    /**
     * 未读消息
     * add('unReadMessage', 'exchangeApi/user/unReadMessage');
     * @param param
     * @returns {*}
     */
    unReadMessage(param = {}) {
        return ajax.get('/exchangeApi/user/message/unread', {
            data: param
        }, false);
    },

    /**
     * 轮训未读消息
     */
    onLoopUnReadMessage: (function() {
        const LOOP_TIME = 10000;
        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback) {
            let that = this;

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return;
            } else {
                loop();
            }


            function loop() {
                that.unReadMessage().then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        // 非调试状态下
                        if (window.app.DEBUG === false) {
                            loop();
                        }
                    }, LOOP_TIME)
                });
            }
        };

    })(),





    /**
     * 轮训KLINE
     */
    onLoopKline: (function() {
        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(callback, param) {
            let that = this;

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return;
            } else {
                loop();
            }


            function loop() {
                that.kline(param).then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        // 非调试状态下
                        if (window.app.DEBUG === false) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
        };

    })(),


    /**
     * k线图
     * @param param
     * @returns {*}
     */
    kline(param = {}) {
        return ajax.getHttpQuote('/trade/kline', {
            data: param
        });
    },

    /**
     * 当前委托
     * @param param
     * @returns {*}
     */
    tradeCoinCurrentList(param = {}) {
        return ajax.get('/exchangeApi/match/match-order/current', {
            data: param
        });
    },

    /**
     * 我的账户信息提醒
     * @param param
     * @returns {*}
     */
    accountMessageList(param = {}) {
        return ajax.get('/exchangeApi/user/message', {
            data: param
        });
    },

    /**
     * 登出
     * @param param
     * @returns {*}
     */
    logout(param = {}) {
        return ajax.send('/exchangeApi/user/logout', {
            data: param
        });
    },

    /**
     * 账户明细列表
     * @param param
     * @returns {*}
     */
    billList(param = {}) {
        return ajax.get('/exchangeApi/asset/finance-detail', {
            data: param
        });
    },

    /**
     * 获取货币地址
     * @param param
     * @param param.assetCode BTC|GOP|USD
     * @returns {*}
     */
    getCoinAddress(param = {}) {
        return ajax.get('/exchangeApi/coin/transfer-in-address', {
            data: param
        });
    },


    /**
     * 所有交易對詳細信息
     * add('getTradeDetail', '/trade/detail');
     * @param param
     * @returns {*}
     */
    getTradeDetail(param = {}) {
        return ajax.getHttpQuote('/trade/detail', {
            data: param
        }, false);
    },

    /**
     * 轮训交易對詳細消息
     */
    onLoopGetTradeDetail: (function() {
        let isRequesting = false;
        let hasRequested = false;
        let callbacks = [];

        return function(callback) {
            // 请求时先将循环开关  打开
            let isLoop = true;
            let that = this;

            let returnObj = {
                clear() {
                    isLoop = false;
                    hasRequested = false;
                    isRequesting = false;
                }
            };

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return returnObj;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return returnObj;
            } else {
                loop();
            }


            function loop() {
                that.getTradeDetail().then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        // 非调试状态下
                        if (window.app.DEBUG === false && isLoop === true) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
            return returnObj;
        };

    })(),




    /**
     * 当前委托
     * @param param
     * @returns {*}
     */
    tradeCoinCurrentList(param = {}) {
        return ajax.get('/exchangeApi/match/match-order/current', {
            data: param
        });
    },
    /**
     * 轮训 当前委托交易
     */
    onLoopGetMyCurOrder: (function() {
        let isRequesting = false;
        let hasRequested = false;

        let callbacks = [];

        return function(reqJson, callback) {
            // 请求时先将循环开关  打开
            let isLoop = true;
            let that = this;

            callbacks.push(callback);

            if (hasRequested === true) {
                if (window.app.DEBUG === true) {
                    loop();
                }
                return;
            } else {
                hasRequested = true;
            }

            if (isRequesting === true) {
                return;
            } else {
                loop();
            }


            function loop() {
                that.tradeCoinCurrentList(reqJson).then((rep) => {
                    isRequesting = false;
                    callbacks.forEach((callback, index) => {
                        callback.call(that, rep);
                    });
                    setTimeout(() => {
                        // 非调试状态下
                        if (window.app.DEBUG === false && isLoop === true) {
                            loop();
                        }
                    }, normalLoopTime);
                });
            }
            return () => {
                // 生命周期结束前   将变量重置初始化
                isLoop = false;
                hasRequested = false;
                isRequesting = false;
            }
        };

    })(),

    /**
     * 所有币种的列表
     */
    assetList(param = {}) {
        return ajax.get('/exchangeApi/coin/configasset-list', {
            data: param
        });
    },

    /**
     * 所有币种的配置列表
     */
    assetConfigList(param = {}) {
        return ajax.get('/exchangeApi/coin/assetprofile-list', {
            data: param
        });
    },


    /**
     * 查询所有交易对
     */
    symbolList(param = {}) {
        return ajax.get('/exchangeApi/match/symbols', {
            data: param
        });
    },

    /**
     * 查询所有交易对的配置
     * @param param
     * @returns {*}
     */
    symbolConfigList(param = {}) {
        return ajax.get('/exchangeApi/match/symbolprofiles', {
            data: param
        });
    },

    /**
     * 获取所有的交易对以及配置
     *
     * let symbolMap = {
     *      BTC_ACT: {
                AMOUNTPRECISION: "4",
                ASSETFEERATE: "0.03",
                HIGHLIGHTNO: "5",
                PRICEPRECISION: "8",
                assetCode1: "BTC",
                assetCode2: "ACT",

                description: "交易对的名称",
                maxAmount1: 100000,
                maxAmount2: 1000000,
                minAmount1: 1,
                minAmount2: 1,
                minPrecision1: 8,
                minPrecision2: 8,

                status: "LISTED",
                symbol: "BTC_ACT",
                title: "ACT/BTC"
           },
           BTC_LTC: {...}
        };

        let symbolList = [
            {
                AMOUNTPRECISION: "4",
                ASSETFEERATE: "0.03",
                HIGHLIGHTNO: "5",
                PRICEPRECISION: "8",
                assetCode1: "BTC",
                assetCode2: "ACT",

                description: "交易对的名称",
                maxAmount1: 100000,
                maxAmount2: 1000000,
                minAmount1: 1,
                minAmount2: 1,
                minPrecision1: 8,
                minPrecision2: 8,

                status: "LISTED",
                symbol: "BTC_ACT",
                title: "ACT/BTC"
            },
            {...}
        ]

     *
     *
     * @param callback
     */
    fetchSymbols(callback) {
        $.when(this.symbolList(), // 币种的交易状态，上线、下线等
            this.symbolConfigList(), // 交易手续费
        ).done((symbolRep, symbolProfileRep) => {

            if (symbolRep.code !== window.CODE.SUCCESS) {
                window.error(symbolRep.msg);
                return;
            }

            if (symbolProfileRep.code !== window.CODE.SUCCESS) {
                window.error(symbolProfileRep.msg);
                return;
            }

            let symbolList = symbolRep.data;
            let symbolProfileList = symbolProfileRep.data;

            let innerObj;
            let symbolMap = {};
            $.map(symbolList, (item, index) => {
                for (let i = 0; i < symbolProfileList.length; i++) {
                    innerObj = symbolProfileList[i];
                    if (item.symbol === innerObj.symbol) {
                        item[innerObj.profileKey] = innerObj.profileValue;
                    }
                }
                item.title = item.assetCode2 + '/' + item.assetCode1;
            });

            let results = [];
            $.map(symbolList, (item, index) => {
                // 仅仅显示status !== INIT以及item.SHOWSTATUS === 'ON'的选项
                if (item.status !== 'INIT' && item.SHOWSTATUS === 'ON') {
                    results.push(item);
                    symbolMap[item.symbol] = item;
                }
            });
            symbolList = results;

            callback(symbolMap, symbolList);

        });

    },

    /**
     * 获取所有资产以及相关配置
        let assetMap = {
            AAC: {
                ASSETCODECONFIRMNUM: "10",
                DEPOSITLEVEL_DEFAULT: "0",  // 0开放，1关闭
                WITHDRAWLEVEL_0: "0",
                WITHDRAWLEVEL_1: "0",
                WITHDRAWLEVEL_2: "-1",
                WITHDRAWMAX: "100",
                WITHDRAWMIN: "0.1",
                WITHDRAWMINFEE: "0.005",
                WITHDRAWPRECISION: "5",
                assetCode: "AAC",
                coinAddressType: null,
                createDate: 1513670565000,
                currencyType: "COIN",
                description: "0",
                id: 54,
                minPrecision: 0,
                name: "AAC",
                status: "LISTED",
                supplyAmount: 33333333333,
                totalAmount: 55555555555555,
                updateDate: 1513670565000,
                webUrl: "0"
            },
            {...}
        };

        let assetList = {
            {
                ASSETCODECONFIRMNUM: "10",
                DEPOSITLEVEL_DEFAULT: "0",  // 0开放，1关闭
                WITHDRAWLEVEL_0: "0",
                WITHDRAWLEVEL_1: "0",
                WITHDRAWLEVEL_2: "-1",
                WITHDRAWMAX: "100",
                WITHDRAWMIN: "0.1",
                WITHDRAWMINFEE: "0.005",
                WITHDRAWPRECISION: "5",
                assetCode: "AAC",
                coinAddressType: null,
                createDate: 1513670565000,
                currencyType: "COIN",
                description: "0",
                id: 54,
                minPrecision: 0,
                name: "AAC",
                status: "LISTED",
                supplyAmount: 33333333333,
                totalAmount: 55555555555555,
                updateDate: 1513670565000,
                webUrl: "0"
            },
            {...}
        }
     * @param callback
     */
    fetchAssets(callback) {

        $.when(this.assetList(), this.assetConfigList()).done((assetListRep, assetConfigListRep) => {

            if (assetListRep.code !== window.CODE.SUCCESS) {
                window.error(assetListRep.msg);
                return;
            }

            if (assetConfigListRep.code !== window.CODE.SUCCESS) {
                window.error(assetConfigListRep.msg);
                return;
            }

            let assetList = assetListRep.data;
            let assetProfileList = assetConfigListRep.data;

            let results = [];
            $.map(assetList, (item, index) => {
                // 仅仅显示status = LISTED的数组
                if (item.status === 'LISTED') {
                    results.push(item);
                }
            });
            assetList = results;

            let innerObj;
            let assetMap = {};
            $.map(assetList, (item, index) => {
                for (let i = 0; i < assetProfileList.length; i++) {
                    innerObj = assetProfileList[i];
                    if (item.assetCode === innerObj.assetCode) {
                        item[innerObj.profileKey] = innerObj.profileValue;
                    }
                }
                assetMap[item.assetCode] = item;
            });

            callback(assetMap, assetList);

        });

    }

};